﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class ShopsController : BaseController
    {
        private readonly ShopsBLL _bll = new ShopsBLL();

        #region 列表

        public ActionResult List()
        {
            if (MagModules.FindAll(t => t.Action == "Create" && t.Controller == "Shops").Count > 0)
            {
                ViewBag.IsCreate = 1;
            }
            else
            {
                ViewBag.IsCreate = 0;
            }
            return View();
        }

        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult Listing(int draw, int start, int length)
        {
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            string direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "Name", "LegalPerson", "LegalPersonMobile", "Address", "Description", "IsActive", "Id" };
            string search = Request["search[value]"];
            int pageIndex = (start / length) + 1;

            TableDataViewDto<ViewShopsDto> theList = _bll.GetPagingList(draw, pageIndex, length, SqlSafe(search),
                orderByColumns[order] + " " + direction, MagModules);

            JsonResult jsonResult = Json(theList);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }

        [HttpPost]
        public JsonResult GetActiveShopList(string keyWords)
        {
            return Json(ShopsBLL.Instance.GetListByName(keyWords, true));
        }

        #endregion

        #region 创建

        public ActionResult Create()
        {
            InitiSet();
            var model = new Shops
            {
                CloseTimeStart = Convert.ToDateTime("1900-01-01"),
                CloseTimeEnd = Convert.ToDateTime("1900-01-01"),
                SalesVolume = 0,
                IsDelete = false,
                Enabled = true,
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection, Shops model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            var now = DateTime.Now;
            if (model.BusinessStatus == 1)
            {
                model.CloseTimeStart = now;
                model.CloseTimeEnd = now;
            }

            var strUploadImage = UploadImage("fileImage", "/Shops/Logo/", 300, 300);
            if (!string.IsNullOrEmpty(strUploadImage)) model.Logo = strUploadImage;

            model.CreatedBy = CurrentUser.Id;
            model.UpdatedBy = CurrentUser.Id;
            model.Created = now;
            model.Updated = now;
            model.IsActive = true;
            if (!string.IsNullOrEmpty(model.Longitude) && !string.IsNullOrEmpty(model.Latitude))
            {
                var coordinateStr = CoordinateTransform.BD_WG84(Convert.ToDouble(model.Longitude), Convert.ToDouble(model.Latitude));
                model.Longitude = coordinateStr[0].ToString();
                model.Latitude = coordinateStr[1].ToString();
                model.IsCoordinateTransform = true;
            }
            if (model.IsHeadquarters)
            {
                model.ParentShopId = 0;
            }
            var newShopId = _bll.Add(model);
            if (newShopId > 0)
            {
                ShopSubsidiaryInfoBLL.Instance.Add(new ShopSubsidiaryInfo
                {
                    ShopId = newShopId,
                    AddTime = now,
                    AccountMoney = 8,//赠送8元余额
                    TotaChargeMoney = 8,//赠送8元余额
                    TotalCanSendCard = 200//赠送200次发卡次数
                });
                //添加赠送充值记录
                ShopMoneyChangeRecordBLL.Instance.Add(new ShopMoneyChangeRecord
                {
                    MxProjectInfoId = 1,
                    AfterMoney = 8,
                    ChangeSource = (int)CloudCardEnum.MerchantMoneyChangeSource.注册店铺系统赠送,
                    ChangeMoney = 8,
                    OperaSource = (int)CloudCardEnum.MerchantMoneyOperaSource.平台,
                    OperaResult = (int)CloudCardEnum.MerchantMoneyOperaResult.操作成功,
                    AddTime = now,
                    ShopId = newShopId
                });

                //将强制上架商品加进来
                var isLanmaSoldCommodityList = CommodityLibBLL.Instance.GetModelList("IsLanmaSold=1");
                foreach (var item in isLanmaSoldCommodityList)
                {
                    var shopCommofity = new ShopCommodity
                    {
                        CommodityLibId = item.Id,
                        ShopId = newShopId,
                        SoldPrice = item.SuggestedPrice,
                        Quantity = 0,
                        DisplaySort = 999,
                        SellingStatus = item.Id != 1,//老大说此处写死，此乃瘤子
                        AddTime = now
                    };
                    ShopCommodityBLL.Instance.Add(shopCommofity);
                }
                return model.Enabled
                        ? RedirectToAction("Create", "McAccounts", new { id = newShopId })
                        : RedirectToAction("List", "Shops");
            }
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 修改

        public ActionResult Update(int id)
        {
            if (id <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var model = _bll.GetModel(id);
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }
            InitiSet();
            if (!string.IsNullOrEmpty(model.Longitude) && !string.IsNullOrEmpty(model.Latitude))
            {
                var coordinateStr = CoordinateTransform.WG84_BD(Convert.ToDouble(model.Longitude), Convert.ToDouble(model.Latitude));
                model.Longitude = coordinateStr[0].ToString();
                model.Latitude = coordinateStr[1].ToString();
            }
            var accountId = _bll.GetShopSuperAccountId(id);
            ViewBag.SuperAccountId = accountId;
            ViewBag.theLogo = ConfigurationManager.AppSettings["ImgFileSitePath"] + model.Logo;
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, Shops model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            if (model.BusinessStatus == 1)
            {
                model.CloseTimeStart = DateTime.Now;
                model.CloseTimeEnd = DateTime.Now;
            }

            string strUploadImage = UploadImage("fileImage", "/Shops/Logo/", 300, 300);
            if (!string.IsNullOrEmpty(strUploadImage)) model.Logo = strUploadImage;

            Shops oriModel = _bll.GetModel(model.Id);
            if (string.IsNullOrEmpty(model.Address))
            {
                model.Address = oriModel.Address;
            }
            if (oriModel.CanFrontView)
            {
                model.CanFrontView = true;
            }
            model.IsHeadquarters = oriModel.IsHeadquarters;
            model.ParentShopId = oriModel.ParentShopId;
            model.UpdatedBy = CurrentUser.Id;
            model.Updated = DateTime.Now;
            if (oriModel.Longitude != model.Longitude || oriModel.Latitude != model.Latitude)
            {
                var coordinateStr = CoordinateTransform.BD_WG84(Convert.ToDouble(model.Longitude), Convert.ToDouble(model.Latitude));
                model.Longitude = coordinateStr[0].ToString();
                model.Latitude = coordinateStr[1].ToString();
                model.IsCoordinateTransform = true;
            }
            bool result = _bll.Update(model);

            if (result)
                return RedirectToAction("List", "Shops");

            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 删除

        [HttpPost]
        public JsonResult Delete()
        {
            string ids = Request["doIds"];
            bool result = _bll.DeleteList(ids);
            if (result)
            {
                //删除McAccount数据
                McAccountsBLL.Instance.DeleteListByShopIds(ids);
            }
            return Json(result);
        }

        #endregion

        /// <summary>
        /// 所有数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetCount()
        {
            var data = _bll.GetTotalCount();
            return Json(data);
        }

        /// <summary>
        /// 检查店铺名称是否已被使用
        /// </summary>
        /// <remarks>2016-08-31 万乐园 创建</remarks>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult CheckShopName(int id, string name)
        {
            var result = true;
            var tempModel = ShopsBLL.Instance.GetModelByName(name);
            if (tempModel != null && tempModel.Id != id)
            {
                result = false;
            }
            return Json(result);
        }

        /// <summary>
        /// 店铺充值
        /// </summary>

        public ActionResult Charge(int id)
        {
            var subsidiaryInfo = ShopSubsidiaryInfoBLL.Instance.GetModelByShopId(id) ?? new ShopSubsidiaryInfo { ShopId = id };
            var sysConfig = SysConfigBLL.Instance.GetModelList()[0];
            ViewBag.CardQuantityPerYuan = sysConfig.CardQuantityPerYuan;
            return View(subsidiaryInfo);
        }

        /// <summary>
        /// 店铺充值
        /// </summary>
        [HttpPost]
        public JsonResult Charge(ShopSubsidiaryInfo model)
        {
            var result = new Result();
            var currentTime = DateTime.Now;
            var subsidiaryInfo = ShopSubsidiaryInfoBLL.Instance.GetModel(model.Id);
            if (subsidiaryInfo == null)
            {
                result.Message = "数据有误，请联系管理员";
                return Json(result);
            }
            var beforeMoney = subsidiaryInfo.AccountMoney;
            var sysConfig = SysConfigBLL.Instance.GetModelList()[0];
            subsidiaryInfo.AccountMoney += model.ChargeMoney;
            subsidiaryInfo.TotaChargeMoney += model.ChargeMoney;
            subsidiaryInfo.TotalCanSendCard += model.ChargeMoney * sysConfig.CardQuantityPerYuan;
            subsidiaryInfo.UpdateTime = currentTime;
            result.Status = ShopSubsidiaryInfoBLL.Instance.Update(subsidiaryInfo);
            if (result.Status)
            {
                //添加充值记录
                ShopMoneyChangeRecordBLL.Instance.Add(new ShopMoneyChangeRecord
                {
                    MxProjectInfoId = 1,
                    BeforeMoney = beforeMoney,
                    AfterMoney = subsidiaryInfo.AccountMoney,
                    ChangeSource = (int)CloudCardEnum.MerchantMoneyChangeSource.充值,
                    ChangeMoney = model.ChargeMoney,
                    OperaUserId = CurrentUser.Id,
                    OperaSource = (int)CloudCardEnum.MerchantMoneyOperaSource.后台账户,
                    OperaResult = (int)CloudCardEnum.MerchantMoneyOperaResult.操作成功,
                    AddTime = currentTime,
                    ShopId = model.ShopId
                });
            }
            return Json(result);
        }

        #region Private Functions 自用函数

        private void InitiSet()
        {
            var lsBusinessStatus = new List<SelectListItem>
            {
                new SelectListItem {Value = "1", Text = "营业中"},
                new SelectListItem {Value = "2", Text = "打烊"}
            };
            ViewBag.lsBusinessStatus = lsBusinessStatus;

            var parentIndustryList = IndustryBLL.Instance.GetModelList("ParentId=0").Select(model => new SelectListItem
            {
                Value = model.Id.ToString(),
                Text = model.Name
            }).ToList();
            ViewBag.ParentIndustryList = parentIndustryList;//一级行业
        }

        #endregion
    }
}